package com.zzw.redisson;

import com.zzw.utils.JsonHelper;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author Administrator
 */
public class RedisHelper implements RedisH {

    private final StringRedisTemplate stringRedisTemplate;
    private final RedissonClient redissonClient;

    public RedisHelper(StringRedisTemplate stringRedisTemplate, RedissonClient redissonClient) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.redissonClient = redissonClient;
    }

    public void setKey(String key, Object value, long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JsonHelper.toJson(value), time, timeUnit);
    }

    public void setWithLogicalExpire(String key, Object value, long time, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setValue(value);
        redisData.setExpire(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JsonHelper.toJson(redisData));
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(5);

    @Override
    public <T, R> R queryWithLogicalExpire(String keyPrefix, T id, Function<T, R> getById, Class<R> type, long time, TimeUnit timeUnit) throws InterruptedException {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(json)) {
            return null;
        }
        RedisData redisData = JsonHelper.readValue(json, RedisData.class);
        R r = JsonHelper.readValue(JsonHelper.toJson(redisData), type);
        if (redisData.getExpire().isAfter(LocalDateTime.now())) {
            return r;
        }
        RLock lock = redissonClient.getLock(key);
        boolean tryLock = lock.tryLock(1, 3, TimeUnit.SECONDS);
        if (tryLock) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R r2 = getById.apply(id);
                    this.setWithLogicalExpire(key, r2, time, timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            });
        }
        return r;
    }
}
